#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lexer.h"
#include "parser.h"
#include "ast.h"
#include "semantic_analyzer.h"
#include "plan_generator.h"
#include "execution.h"
#include "catalog.h"
#include "storage_system.h"

// 测试辅助函数：执行SQL语句并输出结果
int execute_sql(const char* sql, Catalog* catalog, const char* description) {
    printf("\nExecuting: %s\n", sql);
    if (description) {
        printf("Description: %s\n", description);
    }
    
    Lexer* lexer = create_lexer(sql);
    Parser* parser = create_parser(lexer);
    ASTNode* ast = parse_statement(parser);
    
    if (!ast) {
        printf("FAIL: SQL解析失败\n");
        free_parser(parser);
        free_lexer(lexer);
        return -1;
    }
    
    SemanticResult result = analyze_semantics(ast, catalog);
    
    if (!result.success) {
        printf("FAIL: 语义分析失败: %s\n", result.error_message);
        free_semantic_result(result);
        free_ast_node(ast);
        free_parser(parser);
        free_lexer(lexer);
        return -1;
    }
    
    // 对于CREATE TABLE语句，添加到内存catalog
    if (ast->type == NODE_CREATE_TABLE) {
        TableSchema* table_schema = create_table_schema_from_ast(ast);
        add_table_to_catalog(catalog, table_schema);
    }
    
    PlanNode* plan = generate_plan(ast, catalog);
    if (!plan) {
        printf("FAIL: 执行计划生成失败\n");
        free_semantic_result(result);
        free_ast_node(ast);
        free_parser(parser);
        free_lexer(lexer);
        return -1;
    }
    
    int exec_result = execute_plan(plan, catalog);
    if (exec_result == 0) {
        printf("SUCCESS: 执行成功\n");
    } else {
        printf("FAIL: 执行失败，错误码: %d\n", exec_result);
    }
    
    free_plan(plan);
    free_semantic_result(result);
    free_ast_node(ast);
    free_parser(parser);
    free_lexer(lexer);
    
    return exec_result;
}

int main() {
    system("chcp 65001");
    printf("========== 表操作测试程序 ==========\n");
    printf("功能：测试表的创建、插入数据、修改数据、读取数据\n\n");
    
    // 初始化存储系统
    printf("1. 初始化存储系统...\n");
    if (init_storage_system("./data") != STORAGE_OK) {
        printf("FAIL: 存储系统初始化失败\n");
        return 1;
    }
    printf("SUCCESS: 存储系统初始化成功\n");
    
    // 引导系统表
    printf("\n2. 引导系统表...\n");
    if (catalog_bootstrap() != 0) {
        printf("FAIL: 系统表引导失败\n");
        shutdown_storage_system();
        return 1;
    }
    printf("SUCCESS: 系统表引导成功\n");
    
    // 创建内存目录
    printf("\n3. 创建内存目录...\n");
    Catalog* catalog = create_catalog();
    if (!catalog) {
        printf("FAIL: 内存目录创建失败\n");
        shutdown_storage_system();
        return 1;
    }
    printf("SUCCESS: 内存目录创建成功\n");
    
    // 4. 创建表
    printf("\n4. 创建测试表...\n");
    if (execute_sql(
        "CREATE TABLE test_table (id INT, name VARCHAR(50), age INT);", 
        catalog, 
        "创建包含id、name和age三个字段的测试表"
    ) != 0) {
        printf("FAIL: 表创建测试失败\n");
        free_catalog(catalog);
        shutdown_storage_system();
        return 1;
    }
    
    // 5. 插入数据
    printf("\n5. 插入测试数据...\n");
    if (execute_sql(
        "INSERT INTO test_table VALUES (1, '张三', 25);", 
        catalog, 
        "向表中插入一条记录"
    ) != 0) {
        printf("FAIL: 数据插入测试失败\n");
        free_catalog(catalog);
        shutdown_storage_system();
        return 1;
    }
    
    // 6. 读取数据（验证插入）
    printf("\n6. 读取数据（验证插入）...\n");
    if (execute_sql(
        "SELECT * FROM test_table;", 
        catalog, 
        "读取表中所有记录，验证插入是否成功"
    ) != 0) {
        printf("FAIL: 数据读取测试失败\n");
        free_catalog(catalog);
        shutdown_storage_system();
        return 1;
    }
    
    // 7. 修改数据
    printf("\n7. 修改测试数据...\n");
    if (execute_sql(
        "UPDATE test_table SET age = 26, name = '李四' WHERE id = 1;", 
        catalog, 
        "修改已插入的数据"
    ) != 0) {
        printf("FAIL: 数据修改测试失败\n");
        free_catalog(catalog);
        shutdown_storage_system();
        return 1;
    }
    
    // 8. 读取数据（验证修改）
    printf("\n8. 读取数据（验证修改）...\n");
    if (execute_sql(
        "SELECT * FROM test_table WHERE id = 1;", 
        catalog, 
        "读取修改后的数据，验证修改是否成功"
    ) != 0) {
        printf("FAIL: 修改后数据读取测试失败\n");
        free_catalog(catalog);
        shutdown_storage_system();
        return 1;
    }
    
    // 9. 清理资源
    printf("\n9. 清理资源...\n");
    free_catalog(catalog);
    if (shutdown_storage_system() != STORAGE_OK) {
        printf("FAIL: 存储系统关闭失败\n");
        return 1;
    }
    printf("SUCCESS: 资源清理成功\n");
    
    printf("\n========== 表操作测试完成 ==========\n");
    printf("所有测试项均已通过！\n");
    system("pause");
    return 0;
}